package com.yty.order.service.impl;

import com.yty.order.entity.OrderDetail;
import com.yty.order.entity.OrderMaster;
import com.yty.order.exception.OrderRuntimeException;
import com.yty.order.form.OrderDetailForm;
import com.yty.order.form.OrderForm;
import com.yty.order.service.OrderDetailService;
import com.yty.order.service.OrderMasterService;
import com.yty.order.service.OrderService;
import com.yty.order.util.KeyUtil;
import com.yty.order.util.RedisUtil;
import com.yty.product.apidata.OrderDetailInput;
import com.yty.product.apidata.ProductInfoOutput;
import com.yty.product.client.ProductClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMasterService orderMasterService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private ProductClient productClient;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    @Transactional
    public void create(OrderForm orderForm) {
        //判断库存是否充足
        orderForm.getOrderDetails().forEach(detail -> {
            Integer stock = (Integer) redisUtil.get(detail.getProductId());
            if (Objects.isNull(stock))
                return;
            if (stock < detail.getProductQuantity())
                throw new OrderRuntimeException("库存不足，productId:{}，剩余库存:{}", detail.getProductId(), stock);
        });

        //查询商品
        List<String> productIds = orderForm.getOrderDetails().stream()
                .map(OrderDetailForm::getProductId).collect(Collectors.toList());

        Map<String, ProductInfoOutput> productInfoOutputMap = productClient.listForOrder(productIds)
                .stream().collect(Collectors.toMap(ProductInfoOutput::getProductId, v -> v));

        //订单入库
        OrderMaster orderMaster = new OrderMaster();
        //填充表单信息
        BeanUtils.copyProperties(orderForm, orderMaster);
        //填充基本信息
        String orderId = KeyUtil.getUniqueKey();
        orderMaster.setOrderId(orderId);

        //填充商品信息
        List<OrderDetail> orderDetails = orderForm.getOrderDetails().stream()
                .map(detailForm -> {
                    OrderDetail orderDetail = new OrderDetail();
                    //填充通用信息
                    orderDetail.setOrderId(orderId);
                    orderDetail.setDetailId(KeyUtil.getUniqueKey());
                    //填充购买信息
                    orderDetail.fillByDetailForm(detailForm);
                    return orderDetail;
                })
                .map(orderDetail -> orderDetail.fillByProductInfoOutput(productInfoOutputMap.get(orderDetail.getProductId())))
                .collect(Collectors.toList());

        //计算订单总金额
        orderMaster.setOrderAmount(orderDetails.stream()
                .map(orderDetail -> orderDetail.getProductPrice().multiply(new BigDecimal(orderDetail.getProductQuantity())))
                .reduce(BigDecimal.ZERO, BigDecimal::add));

        //扣库存
        productClient.decreaseStock(orderForm.getOrderDetails().stream()
                .map(orderDetailForm -> {
                    OrderDetailInput orderDetailInput = new OrderDetailInput();
                    BeanUtils.copyProperties(orderDetailForm, orderDetailInput);
                    return orderDetailInput;
                }).collect(Collectors.toList()));

        orderMasterService.save(orderMaster);
        orderDetailService.saveBatch(orderDetails);
    }
}
